﻿using AutoMapper;
using DocumentFormat.OpenXml.EMMA;
using MediatR;
using ProduceBasicData.Api.Application.Command.Process;
using ProduceBasicData.Api.Services;
using ProduceBasicData.Domain.FactoryModeling;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;
using ProduceBasicData.Api.Services;

namespace ProduceBasicData.Api.Application.Handler.Process
{
    /// <summary>
    /// 工序维护信息录入处理类
    /// </summary>
    public class CreateProcessHandler : IRequestHandler<CreateProcessCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<ProcessModel> processRepo;
        private readonly IMapper mapper;
        private readonly ICodeRuleService codeRuleService;

        public CreateProcessHandler(IBaseRespository<ProcessModel> processRepo,
            IMapper mapper,ICodeRuleService codeRuleService)
        {
            this.processRepo = processRepo;
            this.mapper = mapper;
            this.codeRuleService = codeRuleService;
        }

        public async Task<ApiResult<int>> Handle(CreateProcessCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res=new ApiResult<int>();
            var model=mapper.Map<ProcessModel>(request);
            model.CreateName=request.CreateName;
            model.CreateTime=DateTime.Now;

            //编码
            if (string.IsNullOrEmpty(model.Processcode))
            {
                var code = await codeRuleService.AutoGenerateCodeAsync("ProduceBasicData.Domain.FactoryModeling.ProcessModel");
                if (!string.IsNullOrEmpty(code))
                {
                    model.Processcode = code;
                }
                else
                {
                    model.Processcode = $"GX{DateTime.Now:yyyyMMddHHmmss}";
                }
            }


            var r=await processRepo.AddAsync(model);
            if (r>0)
            {
                res.Data= r;
                res.Code = ApiEnum.Success;
                res.Msg = "工序维护信息录入成功";
            }
            else
            {
                res.Code = ApiEnum.Failed;
                res.Msg = "工序维护信息录入失败";
            }
            return res;
        }
    }
}
